<?php
/* KAP 0.3 trigger Manager, CSV
file version 2005-06-02 00:10:37
*/

class waktriggerManager extends wakCoreComponent {
// proprietes
	var $default_parameters=array(
		'path'=>'cfg/',
		'file'=>'triggers.wak.txt'
	);
	// expression reguliere de ligne de triggers
	// uri_path;apply_self;apply_children;method;event;priority;params
	//var $ereg_eventname='[a-zA-Z0-9_.:>-]+';
	//var $ereg_line='([a-zA-Z0-9_./-]+)\;((true)|(false))\;((true)|(false))\;((both)|(get)|(post))\;([a-zA-Z0-9_.:>-]+)\;([0-9]{1,3})\;(.*)';
	
	var $C; // reference au controleur principal

// methodes publiques

	// recherche tous les evenements a activer
	function getEvents($callUri=NULL) {
	
		/*$this->C->needLibrary('readcsvfile');
		$data=readcsvfile($this->param['path'].$this->param['file'],';','"');*/
		$file=$this->parameters['path'].$this->parameters['file'];
		
		if (!$lines=file($file)) {
			trigger_error("waktriggerManager: couldn't read events file $file",E_USER_ERROR);
			return false;
		}
		wakLog("triggerManager: events file $file read, ".count($lines)." lines");
		//echo affvar($lines,false);
		$events=array();
		for ($f=0; $f<count($lines); $f++) {
			if (!$data=$this->readCsvLine($lines[$f])) continue;
			// echo affvar($data);
			//if ($data['apply_self']!='true') continue;
			//echo affvar($data);
			if (strtolower($data['method'])!='both' and strtolower($data['method'])!=strtolower(REQUEST_METHOD))
				continue; // wrong method call
			
			if (ereg('^'.$data['uri_path'].'/?$',CALL_URI) and $data['apply_self']=='true') {
				// apply-self
				$events[]=$data;
				// echo wakaffvar($data);
			} else if (ereg('^'.$data['uri_path'].'(/[^/]+)+',CALL_URI) and $data['apply_children']=='true') {
				// parent trigger applying to children
				$events[]=$data;
			} else if ($data['uri_path']=='/' and $data['apply_children']=='true') {
				// home applying to children
				$events[]=$data;
			} else continue; // evt non selectionné
		}
		//echo affvar($events);
		return $events;
	}

// methodes privees

	function readCsvLine($line) {
		// trimming line to remove endline chars etd
		$line=trim($line);
		// trigger line must start by a / (uri path)
		if (!ereg('^/',$line)) return false;
		//echo $line;
		$r=array('params'=>'');
		$fields=split(';;;',$line); //echo affvar($fields,false);
		/*if (count($fields)<8) {
			trigger_error("triggerManager-txt: incorrect trigger line $line");
			return false;
		}*/
		
		switch (true) {
			case (count($fields)<5): return false;
			case (count($fields)<6): $fields[5]=100;
			case (count($fields)<7): $fields[6]=NULL;
			case (count($fields)<8): $fields[7]=NULL;
		}
		$r['uri_path']=$fields[0];
		$r['apply_self']=$fields[1];
		$r['apply_children']=$fields[2];
		$r['method']=$fields[3];
		$r['event']=$fields[4];
		$r['priority']=$fields[5];
		$r['params']=$fields[6];
		$r['result_to']=trim($fields[7]);
		return $r;
	}

}
?>
